package entity;

import database.DBO;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;

/**
 * Created by LLAP on 2017/12/28.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class Security {

    public static int auth = 1;

    public static boolean validateUser(final String name, final String pwd) {
        String password = Security.hash(pwd, "SHA-256");
//        System.out.println(name);
//        System.out.println(password);
        DBO db = new DBO();
        try {
            ResultSet result = db.find(new Object[]{
                    "name = ? and password = ?",
                    name, password
            }, "agent");
            return result.next();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    public static String hash(final String strText, final String strType) {
        String strResult = null;
        if (strText != null && strText.length() > 0) {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                messageDigest.update(strText.getBytes());
                byte byteBuffer[] = messageDigest.digest();
                StringBuffer strHexString = new StringBuffer();
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                strResult = strHexString.toString();
            }
            catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
//        System.out.println(strResult);
        return strResult;
    }
    public static void main(String[] args) {
        System.out.println(Security.hash("123456", "SHA-256"));
    }
}
